(function() {
    var $ = require(L('$')), _ = require(L('_'));
    var enumObj = require(L('enumeration'));

    var win = $.createWindow(L('win_purchases'));
    var ui = $.layout('purchases/view');
    ui.top.add($.ui('partial').scan_and_take_photo());
    var table = ui.table;
    win.add([$.ui('navbar')(false, true), ui.view]);

    sortObj = $.ui('ddl').sortByPurchase(function(e) {
        ui.table.currentSortValue = e;
        ui.table.filter();
    });
    ui.filter.add(sortObj);
    ui.filter.sortObj = sortObj;
    //ui.table.currentSortValue = enumObj.SortTypePurchase.SortBy.value;

    var refineObj = $.ui('ddl').refinePurchase([], function(e) {
        ui.table.currentRefineValue = e;
        ui.table.filter();
    });
    ui.filter.add(refineObj);
    ui.filter.refineObj = refineObj;
    //ui.table.currentRefineValue = enumObj.RefineTypePurchase.Refine.value;

    ui.table.filter = function() {
        $.mask();
        var filteredData = FilterData(ui.table.currentSortValue, ui.table.currentRefineValue, win.data.ProductItem);
        ui.table.render_wrapper(filteredData);
        ui.table.render_rows(filteredData);
        $.mask(false);
    };

    ui.table.render_wrapper = function(data) {
        ui.table.isBuilt = true;
        ui.table.scrollToTop(0);
        ui.title.text = data.length > 1 ? data.length + ' items found' : data.length + ' item found';
    };
    ui.table.render_rows = function(data, limit) {
        limit = limit || data.length;
        limit = Math.min(limit, data.length);
        var tableData = new Array();
        for (var i = 0; i < limit; i++) {
            tableData.push(RenderProduct(data[i], i));
        }
        //tableData.push($.ui('partial').empty_row());
        ui.table.data = tableData;
    };
    ui.table.render_rows_lazy = function(data, startIndex) {
        ui.table.render_rows(data, 5);
    };

    ui.table.reset = function() {
        var length = ui.table.data[0].rows.length;
        var children = ui.table.data[0].rows.slice(0);
        for (var i = 0; i < length; i++) {
            ui.table.remove(children[i]);
        }
    };
    win.reset = function() {
        ui.table.isBuilt = false;
        ui.table.reset();
    };
    win.display = function() {
        var applyDefaultFilter = false;
        if (ui.table.currentSortValue !== enumObj.SortTypePurchase.SortBy.value || ui.table.currentRefineValue !== enumObj.RefineTypePurchase.Refine.value) {
            applyDefaultFilter = true;
        }

        ui.table.currentSortValue = enumObj.SortTypePurchase.SortBy.value;
        ui.table.currentRefineValue = enumObj.RefineTypePurchase.Refine.value;
        ui.filter.sortObj.updateSelectedValue(enumObj.SortTypePurchase.SortBy);
        ui.filter.refineObj.updateSelectedValue(enumObj.RefineTypePurchase.Refine);

        $.opacity_show(ui.view, false);
        $.mask();

        $.webservice().getPurchaseRetailers(function(responseText, nothingNew) {
            if (nothingNew && ui.filter.refineObj) {
                //ui.filter.refineObj
            } else {
                var retailers = new Array();
                var responseObj = JSON.parse(responseText);
                if (responseObj && responseObj.Retailers) {
                    var retailerCount = responseObj.Retailers.length;
                    $.i('retailerCount: ' + retailerCount);
                    for (var i = 0; i < retailerCount; i++) {
                        if (responseObj.Retailers[i].isVisible)
                            retailers.push($.model('name_value')(responseObj.Retailers[i].name, responseObj.Retailers[i].value));
                    }
                    retailers = _.sortBy(retailers, function(item) {
                        return item.name;
                    });
                }
                ui.filter.remove(ui.filter.refineObj);
                ui.filter.refineObj = null;
                var refineObj = $.ui('ddl').refinePurchase(retailers, function(e) {
                    ui.table.currentRefineValue = e;
                    ui.table.filter();
                });
                ui.filter.add(refineObj);
                ui.filter.refineObj = refineObj;
            }
        });

        $.webservice().getPurchases(function(responseText, nothingNew) {
            if (nothingNew && table.isBuilt) {
                Ti.API.info("get purchases goes here");
                if (applyDefaultFilter) {
                    ui.table.reset();
                    ui.title.text = win.data.ItemCount;
                    ui.table.render_rows(win.data.ProductItem);
                }
                $.mask(false);
                $.opacity_show(ui.view);
                return;
            }

            if (ui.table.isBuilt) {
                ui.table.reset();
            }

            win.data = JSON.parse(responseText);
            ui.title.text = win.data.ItemCount;
            ui.table.render_rows(win.data.ProductItem);
            $.opacity_show(ui.view);
            $.mask(false);

            var result = JSON.parse(responseText);
            ui.title.text = result.ItemCount;
        });
    };

    function RenderProduct(product, index) {
        var ui = $.layout('purchases/purchase_row');
        ui.row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
        ui.row.backgroundColor = index % 2 == 1 ? '#f7f7f7' : '#fff';
        ui.image.add($.ui('partial').mydesires_product_image(product.ImageLink));
        ui.productName.text = product.ProductVariantName;
        ui.retailerName.text = product.RetailerFullName;
        ui.purchasePrice.text += product.FormattedUnitPrice;
        ui.purchaseDate.text += product.FormattedOrderDate;
        return ui.row;
    };

    function FilterData(currentSortBy, currentRefine, productItems) {
        var filteredProductItems = new Array();
        if (productItems) {
            var productItemLength = productItems.length;
            if (currentSortBy === enumObj.SortTypePurchase.SortBy.value || currentSortBy === enumObj.SortTypePurchase.Newest.value) {
                if (currentRefine !== enumObj.RefineTypePurchase.ShowAll.value && currentRefine !== enumObj.RefineTypePurchase.Refine.value) {
                    $.i(' SortBy OR Newest - RetailerID: ' + currentRefine);
                    for (var i = 0; i < productItemLength; i++) {
                        if (productItems[i].NewestIndex > 0 && productItems[i].RetailerID === currentRefine) {
                            filteredProductItems.push(productItems[i]);
                        }
                    }
                    filteredProductItems = _.sortBy(filteredProductItems, function(item) {
                        return item.NewestIndex;
                    });
                } else {
                    $.i(' SortBy OR Newest - ShowAll OR Refine');
                    for (var i = 0; i < productItemLength; i++) {
                        if (productItems[i].NewestIndex > 0) {
                            filteredProductItems.push(productItems[i]);
                        }
                    }
                    filteredProductItems = _.sortBy(filteredProductItems, function(item) {
                        return item.NewestIndex;
                    });
                }
            } else if (currentSortBy === enumObj.SortTypePurchase.Oldest.value) {
                if (currentRefine !== enumObj.RefineTypePurchase.ShowAll.value && currentRefine !== enumObj.RefineTypePurchase.Refine.value) {
                    $.i(' Oldest - RetailerID: ' + currentRefine);
                    for (var i = 0; i < productItemLength; i++) {
                        if (productItems[i].OldestIndex > 0 && productItems[i].RetailerID === currentRefine) {
                            filteredProductItems.push(productItems[i]);
                        }
                    }
                    filteredProductItems = _.sortBy(filteredProductItems, function(item) {
                        return item.OldestIndex;
                    });
                } else {
                    $.i(' Oldest - ShowAll OR Refine');
                    for (var i = 0; i < productItemLength; i++) {
                        if (productItems[i].OldestIndex > 0) {
                            filteredProductItems.push(productItems[i]);
                        }
                    }
                    filteredProductItems = _.sortBy(filteredProductItems, function(item) {
                        return item.OldestIndex;
                    });
                }
            }
        }
        return filteredProductItems;
    };

    module.exports = win;
})();
